<?php

namespace App\Http\Controllers;

use App\Rule;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
use Hash;
use DB;
use Illuminate\Support\Facades\Auth;

class SetController extends Controller {

    public function __construct() {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request) {
        $uid=\Auth::id();
        $rules=Rule::where('uid',$uid)->get();
      //  dd($rules);

       return view('admin.home',['rules'=>$rules]);
       // return view('admin.home');
    }

    public function getAll(Request $request) {
        $uid=\Auth::id();
        $user=User::all();
        return response()->json($user);
    }
    public function getRules() {
        $rules=Rule::all();
        return response()->json($rules);
    }
    public function getRule($id) {
        $rules=Rule::where('uid',$id)->get();
        foreach ($rules as $r){
            $rule[]=$r->name;
        }
        $rule = array_flatten($rule);
        return response()->json($rule);
    }
    public function getUser($id) {
        $user=User::find($id);
        return response()->json($user);
    }
    public function add(Requests\FormRequest $request) {

        $adduser['name'] = $request->input('name');
        $adduser['email'] = $request->input('email');
        $adduser['password'] = Hash::make($request->input('password'));
        $user=User::create($adduser);
        $addr['uid']=$user->id;
        if ($request->input('rule')){
           $rule=$request->input('rule');
            foreach ($rule as $r){
                $addr['name']=$r;
                Rule::create($addr);
            }
        }

    }
    public function del ($id) {
        $user=User::find($id);
        $user->delete();
    }

    public function edit($id, Requests\FormRequest3 $request) {
        $adduser = User::find($id);
        $adduser->password = Hash::make($request->input('password'));
        $adduser->name = $request->input('name');
        $adduser->save();
        Rule::where('uid',$id)->delete();
        $addr['uid']=$id;
        if ($request->input('rule')){
            $rule=$request->input('rule');
            foreach ($rule as $r){
                $addr['name']=$r;
                Rule::create($addr);
            }
        }

    }



    
}
